<template>
	<div class="login-container">
		<div class="login">
			<div class="title">平台端登录</div>
			<el-form
				:model="loginForm"
				ref="loginFormRef"
				label-width="80px"
				style="width: 300px"
				@submit.prevent="handleLogin"
				class="form"
			>
				<el-form-item
					prop="username"
					:rules="[{ required: true, message: '请输入账号', trigger: 'blur' }]"
				>
					<template #label>
						<svg-icon icon-class="用户名" />
					</template>
					<el-input v-model="loginForm.username" placeholder="请输入账号" />
				</el-form-item>

				<el-form-item
					prop="password"
					:rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
				>
					<template #label>
						<svg-icon icon-class="密码" />
					</template>
					<el-input
						v-model="loginForm.password"
						type="password"
						placeholder="请输入密码"
					/>
				</el-form-item>

				<el-form-item
					prop="captcha"
					:rules="[
						{ required: true, message: '请输入验证码', trigger: 'blur' },
					]"
					style="position: relative"
				>
					<template #label>
						<div
							style="
								position: absolute;
								top: 50%;
								left: 50px;
								margin-top: -16px;
							"
						>
							<svg-icon icon-class="验证码" size="1.2em" />
						</div>
					</template>
					<el-input
						v-model="loginForm.captcha"
						placeholder="验证码"
						clearable
						maxlength="5"
						@input="(v) => (loginForm.captcha = v.replace(/[^a-zA-Z0-9]/g, ''))"
						@clear="onClear()"
					>
						<template #append>
							<img :src="captchaUrl" @click="getCaptcha()" class="captchaImg" />
						</template>
					</el-input>
				</el-form-item>

				<el-form-item label="" prop="password">
					<el-checkbox v-model="isRemember">
						<span style="margin-right: 5px">记住密码</span></el-checkbox
					>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" native-type="submit">登录</el-button>
				</el-form-item>
			</el-form>
		</div>

		<div class="footer">
			<span>Copyright © 2025</span>
			<a href="https://beian.miit.gov.cn" target="_blank" class="aLink"
				>浙ICP备1234567号-4
			</a>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { store } from '@/store/index' // Pinia Store
import { lStorage } from '@/utils/storage'
import Cookies from 'js-cookie'
import { login } from '@/api/user.ts'
// import CryptoJS from 'crypto-js'
import { getUUID } from '@/utils/js/index'

const router = useRouter()
const userStore = store.useUserStore()

const captchaUrl = ref('')

const loginForm = reactive({
	username: Cookies.get('WXAI_USER_NAME') || '',
	password: Cookies.get('WXAI_PASS_WORD') || '',
	captcha: '', // 验证码
	uuid: '', // uuid
})

const isRemember = ref(
	(function () {
		try {
			const value = Cookies.get('WXAI_IS_REMEMBER')
			if (value === undefined) return false
			// 尝试解析 JSON，但考虑到 cookie 中的布尔值可能是简单的 "true" 或 "false" 字符串
			return JSON.parse(value)
		} catch (error) {
			// 如果解析失败，返回默认值
			console.error('Error parsing isRemember cookie:', error)
			return false
		}
	})()
)

const loginFormRef = ref(null)

// 清除事件
const onClear = () => {
	loginForm.captcha = loginForm.captcha == 0 ? undefined : loginForm.captcha
}

// 获取验证码
const getCaptcha = () => {
	loginForm.uuid = getUUID()
	loginForm.captcha = ''
	captchaUrl.value =
		import.meta.env.VITE_APP_BASE_API + '/captcha.jpg?uuid=' + loginForm.uuid
}

const handleLogin = async () => {
	loginFormRef.value.validate(async (valid) => {
		if (valid) {
			// 是否记住密码
			if (isRemember.value) {
				Cookies.set('WXAI_IS_REMEMBER', isRemember.value, {
					expires: 7,
				})
				Cookies.set('WXAI_USER_NAME', loginForm.username, {
					expires: 7,
				})
				Cookies.set('WXAI_PASS_WORD', loginForm.password, {
					expires: 7,
				})
			} else {
				Cookies.remove('WXAI_IS_REMEMBER')
				Cookies.remove('WXAI_USER_NAME')
				Cookies.remove('WXAI_PASS_WORD')
			}
			try {
				// 模拟接口
				const params = JSON.parse(JSON.stringify(loginForm))
				// params.password = CryptoJS.MD5(params.password).toString()
				const data = await login(params)

				if (data.code === 0) {
					const fakeToken = data.token

					// 保存 Token 和用户信息到本地存储
					lStorage.set('WXAI_USER_TOKEN', fakeToken)
					// 保存到 Cookie 中
					Cookies.set('WXAI_USER_TOKEN', fakeToken, {
						expires: 7,
					})
					// 更新 Pinia Store
					userStore.setToken(fakeToken)

					// 保存 Token 和用户信息到本地存储
					lStorage.set('WXAI_USER_INFO', userInfo)
					// 保存到 Cookie 中
					Cookies.set('WXAI_USER_INFO', JSON.stringify(userInfo), {
						expires: 7,
					})
					// 更新 Pinia Store
					userStore.setUserInfo(userInfo)

					ElMessage.success('登录成功！')

					nextTick(() => {
						router.push('/index')
					})
				} else {
					getCaptcha()
				}
			} catch (error) {
				if (error.msg.includes('验证码')) {
					getCaptcha()
				}
			}
		} else {
			ElMessage.error('请填写必填项')
		}
	})
}
onMounted(() => {
	getCaptcha()
})
</script>

<style scoped lang="scss">
.login-container {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	position: relative;
	background-color: rgba(229, 229, 229);
}

.login {
	width: 400px; /* 增加宽度 */

	border: 1px solid #eee;
	border-radius: 8px;
	background: #fff;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	border-radius: 10px;

	:deep(.el-form-item__label) {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		&:before {
			content: '' !important;
		}
	}
	:deep(.el-input-group__append) {
		padding: 0;
	}
}

.title {
	font-size: 24px;
	font-weight: bold;
	display: flex;
	justify-content: center;
	align-items: center;
	color: white;
	width: 100%;
	background-color: rgba(51, 51, 51);
	height: 100px;
	border-top-left-radius: 8px;
	border-top-right-radius: 8px;
	margin-bottom: 20px;
}

.form {
	width: 100% !important;
	.el-form-item {
		margin-bottom: 20px;
		width: 80%;
	}
}

.el-button {
	width: 100%;
}

.captchaImg {
	width: 100px;
	height: 32px;
}

:deep(.el-checkbox__input.is-checked) .el-checkbox__inner {
	color: #fff !important;
	background-color: #a357d7 !important;
	border-color: #a357d7 !important;
}
:deep(.el-checkbox__label) {
	color: #a357d7 !important;
}

.footer {
	position: absolute;
	bottom: 0;
	height: 40px;
	background-color: rgba(0, 0, 0, 0.2);
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	color: white;
	font-size: 12px;
	.aLink {
		text-decoration: none;
		margin-left: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
		// 鼠标悬停
		&:hover {
			color: #a357d7;
		}
		// 未被访问链接
		&:link {
			color: white;
		}
		// 已点击的链接
		// &:visited {
		// 	color: #a357d7;
		// }
		// 鼠标按下
		&:active {
			color: white;
		}
	}
}
</style>
